package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
// import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * MyBatis-Plus 配置
 * 
 * @author ruoyi
 */
@Configuration
public class MyBatisPlusConfig
{
    /**
     * MyBatis-Plus 拦截器配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() 
    {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        //interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * MyBatis-Plus 全局配置
     */
    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        // 设置字段策略，忽略 null 值字段
        dbConfig.setInsertStrategy(com.baomidou.mybatisplus.annotation.FieldStrategy.NOT_NULL);
        dbConfig.setUpdateStrategy(com.baomidou.mybatisplus.annotation.FieldStrategy.NOT_NULL);
        // 注意：在3.5.12版本中，setSelectStrategy方法已被移除
        // dbConfig.setSelectStrategy(com.baomidou.mybatisplus.annotation.FieldStrategy.NOT_EMPTY);
        
        // 设置字段命名策略为下划线转驼峰
        dbConfig.setColumnFormat("`%s`");
        
        globalConfig.setDbConfig(dbConfig);
        return globalConfig;
    }

    /**
     * MyBatis-Plus SqlSessionFactory 配置
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, GlobalConfig globalConfig) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setGlobalConfig(globalConfig);
        
        // 设置mapper文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactory.setMapperLocations(resolver.getResources("classpath*:mapper/**/*Mapper.xml"));
        
        // 设置类型别名包
        sqlSessionFactory.setTypeAliasesPackage("com.ruoyi.**.domain");
        
        return sqlSessionFactory.getObject();
    }
}